package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.Question;
import com.tanhua.model.domain.Settings;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.SettingsVo;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ck
 * @date 2021/11/11 21:40
 */
@Service
public class SettingsService {

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private SettingsApi settingsApi;

    @DubboReference
    private BlackListApi blackListApi;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    //查询通用设置
    public SettingsVo settings() {
        SettingsVo settingsVo = new SettingsVo();
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        settingsVo.setId(userId);
        //2、获取用户手机号码
        User user = userApi.getUser(userId);
        settingsVo.setPhone(user.getMobile());
        //3、获取用户的陌生人问题
        Question question = questionApi.fingByUserId(userId);
        String txt = question == null ? "你喜欢java吗?" : question.getTxt();
        settingsVo.setStrangerQuestion(txt);
        //4、获取用户的app通知开关数据
        Settings settings = settingsApi.fingByUserId(userId);
        if (settings != null) {
            settingsVo.setGonggaoNotification(settings.getGonggaoNotification());
            settingsVo.setPinglunNotification(settings.getPinglunNotification());
            settingsVo.setLikeNotification(settings.getLikeNotification());
        }
        return settingsVo;
    }

    //设置陌生人问题
    public void saveQuestion(String content) {
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        //2、调用api查询当前用户的陌生人问题
        Question question = questionApi.fingByUserId(userId);
        //3、判断问题是否存在
        if (question == null) {
            //3.1 如果不存在 保存
            question = new Question();
            question.setUserId(userId);
            question.setTxt(content);
            questionApi.save(question);
        } else {
            //3.2 如果存在 更新
            question.setTxt(content);
            questionApi.updateWithQuestion(question);
        }

    }

    //通知设置
    public void saveSettings(Map map) {
        boolean likeNotification = (boolean) map.get("likeNotification");
        boolean pinglunNotification = (boolean) map.get("pinglunNotification");
        boolean gonggaoNotification = (boolean) map.get("gonggaoNotification");
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        //2、根据用户id查询用户通知设置
        Settings settings = settingsApi.fingByUserId(userId);
        //3、判断通知是否存在
        if (settings == null) {
            //3.1 如果不存在，保存
            settings = new Settings();
            settings.setUserId(userId);
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settingsApi.save(settings);
        }else {
            //3.2 如果存在，更新
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settingsApi.update(settings);
        }
    }

    //分页查询黑名单列表
    public PageResult blacklist(int page, int pageSize) {
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、调用api查询用户的黑名单分页列表
        IPage<UserInfo> iPage = blackListApi.findByUserId(userId,page,pageSize);
        //3、对象的转化，将查询的IPage对象的内容封装到PageResult中
        Long total = iPage.getTotal();

        List<UserInfo> records = iPage.getRecords();
/*        List list = new ArrayList();
        for (UserInfo userInfo : records) {
            list.add(userInfo.getAvatar());
            list.add(userInfo.getNickname());
            list.add(userInfo.getGender());
            list.add(Integer.parseInt(userInfo.getAge()));
        }*/

        PageResult pageResult = new PageResult(page,pageSize,total,records);
        return pageResult;
    }

    //取消黑名单
    public void deleteBlackList(Long blackUserId) {
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        //2、调用api删除
        blackListApi.delete(userId,blackUserId);
    }

    public void getVerificationCode() {
        //1、获取当前手机号
        String mobile = UserHolder.getMobile();
        //2、设置验证码
        String code = "225566";
        //3、存入redis
        redisTemplate.opsForValue().set("CHECK_CODE_" + mobile, code, Duration.ofMinutes(5));
    }

    public Map<String,Boolean> checkVerificationCode(String mobile,String verificationCode) {
        System.out.println(mobile);
        Map<String,Boolean> retMap = new HashMap();
        //2、从redis中得到存入的验证码
        String code = redisTemplate.opsForValue().get("CHECK_CODE_" + mobile);
        if (StringUtils.isEmpty(code) || !code.equals(verificationCode)){
            //验证码无效
            retMap.put("verification",false);
            return retMap;
        }
        retMap.put("verification",true);
        //3、删除redis中的验证码
        redisTemplate.delete("CHECK_CODE_"+mobile);

        return retMap;
    }

    public void updateWithPhone(String newPhone) {
        //1、获取用户数据
        User user = userApi.findByMobile(newPhone);
        if (user != null){
            throw  new BusinessException(ErrorResult.builder().build());
        }
        User user1 = new User();
        user1.setId(UserHolder.getUserId());
        user1.setMobile(newPhone);
        //2、调用api实现修改操作
        userInfoApi.updateWithPhone(user1);
    }
}
